<template>
  <div>
      <!-- 表头分页查询条件， shadow="never" 指定 card 卡片组件没有阴影 -->
      <el-card shadow="never" class="mb-5">
          <!-- flex 布局，内容垂直居中 -->
          <div class="flex items-center flex-col md:flex-row">
              <el-text>标签名称</el-text>
              <div class="mb-2 ml-1 w-52 mr-1 md:ml-3 md:w-52 md:mr-5 md:mb-0">
                <el-input v-model="searchTagName" placeholder="请输入（模糊查询）" />
              </div>

              <el-text>创建日期</el-text>
              <div class="ml-1 w-30 mr-1 mb-2 md:ml-3 md:w-30 md:mr-5 md:mb-0">
                  <!-- 日期选择组件（区间选择） -->
                  <el-date-picker :shortcuts="shortcuts" @change="datepickerChange" style="width: 260px;" v-model="pickDate" type="daterange" range-separator="至" start-placeholder="开始时间"
                      end-placeholder="结束时间" size="default" />
              </div>

              <div>
                <el-button type="primary" class="ml-3" :icon="Search" @click="getTableData">查询</el-button>
                <el-button class="ml-3" :icon="RefreshRight" @click="onReset">重置</el-button>
              </div>
          </div>
      </el-card>
      <!-- 表格 -->
      <el-card shadow="never">
        <!-- 新增按钮 -->
        <div class="mb-5">
          <el-button type="primary" @click="addTagBtnClick">
            <el-icon class="mr-1"><Plus /></el-icon>
            新增</el-button>
        </div>
        <!-- 分页列表 -->
        <el-table :data="tableData" border stripe style="width: 100%" v-loading="tableLoading">
          <el-table-column prop="name" label="标签名称" width="180">
            <template #default="{row}">
              <el-tag class="ml-2" :type="getBgColor()"> {{ row.name }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="articlesTotal" label="文章数" width="100" />
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作">
            <template #default="{row}">
              <el-button size="small" @click="editTagSubmit(row)">
                <el-icon class="mr-1"><Edit/></el-icon>
                编辑
              </el-button>
              <el-button type="danger" size="small" @click="deleteTagSubmit(row)">
                <el-icon class="mr-1"><Delete/></el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="mt-10 flex justify-center">
            <el-pagination v-model:current-page="current" v-model:page-size="size" :page-sizes="[10, 20, 50]"
            :small="false" :background="true" layout="total, sizes, prev, pager, next, jumper"
            :total="total" @size-change="handleSizeChange" @current-change="getTableData"/>
        </div>
        <!-- <el-dialog width="40%" v-model="dialogVisible" title="添加文章分类" :draggable ="true" :close-on-click-modal="false" :close-on-press-escape="false">
          <el-form :model="form" :rules="rules" ref="formRef">
            <el-form-item label="分类名称" prop="name" label-width="80px">
              <el-input v-model="form.name" placeholder="请输入分类名称" maxlength="20" show-word-limit clearable ></el-input>
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="onSubmit">新增</el-button>
            </span>
          </template>
        </el-dialog> -->
      </el-card>
      <!-- 添加标签 -->
      <FormDialog ref="formDialogRef" title="添加文章标签" destroyOnClose @submit="addSubmit">
          <el-form ref="formRef" :model="form">
            <el-form-item prop="name" size="large">
              <el-tag
                class="mx-1"
                v-for="tag in dynamicTags"
                :key="tag"
                closable
                :disable-transitions="false"
                @close="handleClose(tag)"
              >
                {{ tag }}
              </el-tag>
              <span class="w-20">
                <el-input
                  v-if="inputVisible"
                  ref="InputRef"
                  v-model="inputValue"
                  class="ml-1 w-20"
                  size="small"
                  @keyup.enter="handleInputConfirm"
                  @blur="handleInputConfirm"
                />
                <el-button v-else class="button-new-tag" size="default" @click="showInput">
                  + 添加标签
                </el-button>
              </span>
            </el-form-item>
          </el-form>
      </FormDialog>

      <!-- 修改标签 -->
      <FormDialog ref="formEditDialogRef" title="修改文章标签" destroyOnClose @submit="updateSubmit">
        <el-form ref="formRef" :rules="rules" :model="updateForm">
            <el-form-item label="分类名称" prop="name" label-width="80px" size="large">
                <el-input v-model="updateForm.name" placeholder="请输入分类名称" maxlength="20" show-word-limit clearable/>
            </el-form-item>
        </el-form>
      </FormDialog>
  </div>
</template>

<script setup>
import FormDialog from '@/components/FormDialog.vue'
// 引入所需图标
import { Search, RefreshRight, Plus, Delete } from '@element-plus/icons-vue'
import { ref, reactive, nextTick } from 'vue';
import moment from 'moment'
import { getTagPageList, addTag, deleteTag, showTag, updateTag } from '@/api/admin/tag'
import { showMessage, showModel} from '@/composables/util'
// 表格加载loading
const tableLoading = ref(false)
// 新增标签弹框引用
const formDialogRef = ref(null)
// 编辑标签弹框引用
const formEditDialogRef = ref(null)
// 新增标签按钮点击事件
const addTagBtnClick = () => {
    // 先删除表单里的数据
    form.name = ''
    // 拿到ref绑定的组件中的open方法
    formDialogRef.value.open()
}

// 添加文章标签的表单对象
const form = reactive({
  tags: []
})

// 编辑标签的表单对象
const updateForm = reactive({
  id: '',
  name: ''
})

// 添加文章标签的表单引用
const formRef = ref(null)

// 表格数据
const tableData = ref([])

// 当前页码，给了一个默认值 1
const current = ref(1)
// 总数据量，给了个默认值 0
const total = ref(0)
// 每页显示的数据量，给了个默认值 10
const size = ref(10)

// 分页查询的标签名称
const searchTagName = ref('')
// 日期
const pickDate = ref('')

// 查询条件：开始结束时间
const startDate = reactive({})
const endDate = reactive({})


const shortcuts = [
    {
        text: '最近一周',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            return [start, end]
        },
    },
    {
        text: '最近一个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            return [start, end]
        },
    },
    {
        text: '最近三个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            return [start, end]
        },
    },
]

// 监听日期组件改变事件，并将开始结束时间设置到变量中
const datepickerChange = (e) => {
    startDate.value = moment(e[0]).format('YYYY-MM-DD')
    endDate.value = moment(e[1]).format('YYYY-MM-DD')

    console.log('开始时间：' + startDate.value + ', 结束时间：' + endDate.value)
}

// 获取分页数据
const getTableData = async () => {
  const data = {
    current: current.value,
    size: size.value,
    name: searchTagName.value,
    startDate: startDate.value,
    endDate: endDate.value
  }
  // 显示loading
  tableLoading.value = true
  const res = await getTagPageList(data)
  if (res.success == true) {
    tableData.value = res.data
    current.value = res.current
    size.value = res.size
    total.value = res.total
  }
  // 隐藏loading
  tableLoading.value = false
}

getTableData()


// 点击重置
const onReset = () => {
  searchTagName.value = ''
  startDate.value = ''
  endDate.value = ''
  pickDate.value = ''
  getTableData()
}

// 新增标签
const addSubmit = async () => {
  // 显示提交按钮 loading
  formDialogRef.value.showBtnLoading()
  form.tags = dynamicTags.value
  const res = await addTag(form)
  if (res.success == true) {
    showMessage('添加成功')
    // 添加成功后将表单中的标签名称置空
    form.tags = []
    dynamicTags.value = []
    // 隐藏对话框
    formDialogRef.value.close()
    // 重新请求分页接口，渲染数据
    getTableData()
  } else {
    // 获取服务端返回的错误信息
    const message = res.message
    // 提示错误消息
    showMessage(message, 'error')
  }
  // 隐藏提交按钮 loading
  formDialogRef.value.closeBtnLoading()
}

// 删除标签
const deleteTagSubmit = async (row) => {
  await showModel('是否确定要删除该标签？')
  const res = await deleteTag(row.id)
  if (res.success == true) {
    showMessage('删除成功')
    // 重新请求分页接口，渲染数据
    getTableData()
  } else {
    // 获取服务端返回的错误消息
    const message = res.message
    // 提示错误消息
    showMessage(message, 'error')
  }
}

// 编辑标签回显
const editTagSubmit = async (row) => {
  // 先删除表单里的数据
  updateForm.name = ''
  // 拿到ref绑定的组件中的open方法
  formEditDialogRef.value.open()
  const res = await showTag(row.id)
  if (res.success) {
    updateForm.name = res.data
    updateForm.id = row.id
  } else {
    showMessage(res.message, 'error')
  }
}

// 编辑-修改标签
const updateSubmit = async () => {
  await formRef.value.validate()
  // 显示提交按钮 loading
  formEditDialogRef.value.showBtnLoading()
  const res = await updateTag(updateForm)
  if (res.success) {
    showMessage('修改成功')
    // 隐藏对话框
    formEditDialogRef.value.close()
    // 重新请求分页接口，渲染数据
    getTableData()
  } else {
    // 获取服务端返回的错误信息
    const message = res.message
    // 提示错误消息
    showMessage(message, 'error')
  }
  // 隐藏提交按钮 loading
  formEditDialogRef.value.closeBtnLoading()
}



// 标签输入框值
const inputValue = ref('')
// 已输入的标签数组
const dynamicTags = ref([])
// 标签输入框是否显示
const inputVisible = ref(false)
// 标签输入框的引用
const InputRef = ref('')

const handleClose = (tag) => {
  dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
}

const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value.input.focus()
  })
}

const handleInputConfirm = () => {
  if (inputValue.value) {
    dynamicTags.value.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
}

// 底部每页展示数量变化时
const handleSizeChange = (chooseSize) => {
  size.value = chooseSize
  // 重新获取分页数据
  getTableData()
}

const colorList = [
  'primary',
  'success',
  'info',
  'warning',
  'danger',
]

const getBgColor = () => {
  let n = Math.floor(Math.random() * 11)
  return colorList[n]
}

</script>
